<?php

namespace App\Module\Api\Controllers;
use App\Exceptions\Customize\ParamsException;
use App\Jobs\SendMsg;
use App\Module\Api\Controllers\Request\SmsCodeRequest;
use App\Module\Api\Validator\SmsCodeValidator;
use App\System\Base\Services\TokenService;
use App\System\Base\Services\SmsService;
use App\System\Cis\Repositories\CisUserRepository;
use Gregwar\Captcha\CaptchaBuilder;

/**
 *发送验证码
 */
class SmsCodeController extends Controller
{

    public function __construct()
    {
        $this->query = new SmsCodeRequest();
        parent::__construct();

    }

    public function index()
    {
        (new SmsCodeValidator())->check();
        if ($this->query->type == 2){
//            图形验证码生成
           $builder = new CaptchaBuilder();
            $builder->build($width = 100, $height = 40, $font = null);
//           获取验证码内容
            $phrase = $builder->getPhrase();
//            验证码存入Cache
            $cache['captcha'] = $phrase;
            ob_end_clean();
            \Cache::put(request()->s,$cache,config('app.cache_time'));
            header("Cache-Control: no-cache, must-revalidate");
            header('Content-Type: image/jpeg');
            $builder->output();
//            echo 'done!';die;
        }

//         $sms = SmsService::getInstance();
        //验证图形验证码

        $cache = \Cache::get(request()->s);

        if (!isset($cache['captcha'])||strtolower($this->query->captchaCode) != strtolower($cache['captcha'])){
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '验证码错误',
            ]);
        }
//        短信队列
        $this->dispatch(new SendMsg($this->query->mobile,$this->query->action,[]));
//         $res = $sms->SmsSend($this->query->mobile,$this->query->action);

        return apiResponse(['d'=>'发送成功']);
    }
}
